<script setup lang="ts">
  import type { InputOnBlurEvent } from '@uni-helper/uni-app-types/index'
  import { loginByPasswordApi } from '@/api/user'
  import { ref } from 'vue'
  import { useCounterStore } from '@/stores/counter'
  const store = useCounterStore()
  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })
  const isAgree = ref(false)
  const form = ref<UniHelper.UniFormsInstance>()
  const aaa = ref<UniHelper.UniFormsItemInstance>()
  const bbb = ref<UniHelper.UniFormsItemInstance>()
  // 定义表单数据对象
  const formdata = ref({
    mobile: '13230000003',
    password: '',
  })
  // 定义表单验证规则！！
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号码' },
        { pattern: '^[1][3-8][0-9]{9}$', errorMessage: '手机号码格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入密码' },
        { pattern: '^[a-zA-Z0-9]{8}$', errorMessage: '密码格式不正确' },
      ],
    },
  }
  const onSubmit = async () => {
    // 用form组件的统一的校验功能 (自动校验多个字段)

    await form.value?.validate?.()
    if (!isAgree.value) {
      // 登录成功
      uni.showToast({ title: '您还没有勾选用户协议', icon: 'none' })
      return
    }

    // 验证都通过了
    console.log('验证都通过了')
    const res = await loginByPasswordApi(formdata.value)
    console.log(res)
    store.setToken(res.token)

    // 跳转到我的页面
    uni.switchTab({ url: '/pages/index/index' })
  }
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formdata" :rules="formRules">
    <uni-forms-item name="mobile" ref="aaa">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        v-model="formdata.mobile"
        placeholder-style="color: #C3C3C5"
        @blur="(e:InputOnBlurEvent) => aaa?.onFieldChange?.(e.detail.value)"
      />
    </uni-forms-item>
    <uni-forms-item name="password" ref="bbb">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        v-model="formdata.password"
        placeholder-style="color: #C3C3C5"
        @blur="(e:InputOnBlurEvent) => bbb?.onFieldChange?.(e.detail.value)"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
